package cn.hzking.gjmall.activitys.second;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fingdo.statelayout.StateLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.hzking.gjmall.R;
import cn.hzking.gjmall.adpters.category.CateGoryGoodListAdapter;
import cn.hzking.gjmall.base.ColorStatuBarActivity;
import cn.hzking.gjmall.bean.CategoryListBean;
import cn.hzking.gjmall.net.RetrofitFactory;
import cn.hzking.gjmall.net.base.GjCustomStateViewObserver;
import cn.hzking.gjmall.utils.SwipeRefreshLayoutUtils;

/**
 * 商品分类页一级条目点击进入的页面
 */
public class CateGoryGoodListActivity extends ColorStatuBarActivity {
    private final static String CATEGORYID = "categoryId";//一级条目id
    private final static String TYPE = "type";//要显示的是一级条目点击进入的还是二级条目点击进入的
    @Bind(R.id.back_search)
    RelativeLayout backSearch;
    @Bind(R.id.search_et)
    TextView searchEt;
    @Bind(R.id.category_goodlist_ll)
    LinearLayout categoryGoodlistLl;
    @Bind(R.id.recyclerview)
    RecyclerView recyclerview;
    @Bind(R.id.refrsh)
    SwipeRefreshLayout refrsh;
    @Bind(R.id.statlayout)
    StateLayout statlayout;
    private int subCategoryId;//二级条目id
    private ArrayList<String> categoryIds;//一级条目id
    private int type;//0表示从全部进入的 1表示从二级列表进入的
    private int currentPage = 1;
    private CateGoryGoodListAdapter cateGoryGoodListAdapter;
    private TextView toolsTextViews[]; //textview的集合
    private View views[];   //整个view的集合
    private String flag = "all";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_cate_gory_good_list);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        type = intent.getIntExtra(TYPE, -1);
        categoryIds = intent.getStringArrayListExtra(CATEGORYID);
        SwipeRefreshLayoutUtils.initRefreshLayout(refrsh);
        ArrayList<String> itemContents = intent.getStringArrayListExtra("itemContent");
        categoryGoodlistLl.removeAllViews();
        views = new View[itemContents.size()];
        toolsTextViews = new TextView[itemContents.size()];
        for (int i = 0; i < itemContents.size(); i++) {
            View inflate = View.inflate(this, R.layout.item_categorylist_view, null);
            inflate.setTag(i);
            TextView textView = inflate.findViewById(R.id.item_textview);
            views[i] = inflate;
            toolsTextViews[i] = textView;
            if(i == 0){
                textView.setSelected(true);
            }
            textView.setText(itemContents.get(i));
            categoryGoodlistLl.addView(inflate);
            inflate.setOnClickListener(listener);
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        recyclerview.setLayoutManager(gridLayoutManager);
        cateGoryGoodListAdapter = new CateGoryGoodListAdapter(R.layout.item_goodlist, null);
        recyclerview.setAdapter(cateGoryGoodListAdapter);
        //点击全部进入的分类列表页
        getNetData(flag, true, false, true, true, null, null, null);
        initLister();

    }

    private void initLister() {
        //返回按钮
        backSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post("返回");
                finish();
            }
        });
        //刷新
        refrsh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = 1;
                getNetData(flag, false, true, false, true, null, null, null);

            }
        });

        //上拉加载更多
        cateGoryGoodListAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                getNetData(flag, false, false, false, true, null, null, null);
            }
        });
    }

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            currentPage = 1;
            int tag = (int) v.getTag();//在线性布局中的位置
            //点击变化按钮状态
            checkSecect(tag);
            if(type == 0) {//一级条目点击进入的
                if (tag != 0) {//不是点击全部
                    String s = categoryIds.get(tag);
                    flag = s;
                    getNetData(flag, false, false, true, true, null, null, null);

                } else {//点击全部进入
                    flag = "all";
                    getNetData(flag, false, false, true, true, null, null, null);
                }
            }else if(type == 1){//从二级条目进入的

            }


        }
    };

    private void checkSecect(int tag) {
        for (int i = 0; i < toolsTextViews.length; i++) {
            toolsTextViews[i].setSelected(false);
        }
        toolsTextViews[tag].setSelected(true);
    }

    public void getNetData(String secondType, boolean isFristInit, boolean isRefrsh, boolean isShowDialog, boolean isCancel, View emptyView, View onNetView, View errorView) {
        HashMap<String, String> parms = new HashMap<>();
        if ("all".equals(secondType)) {//点击全部的请求
            parms.put("pageIndex", String.valueOf(currentPage));

        } else {//点击别的条目的请求
            parms.put("pageIndex", String.valueOf(currentPage));
            parms.put("categoryId", secondType);
        }
        RetrofitFactory.getInstant().API()
                .getCateGoryList(parms)
                .compose(this.<CategoryListBean>setThread())
                .subscribe(new GjCustomStateViewObserver<CategoryListBean>(this, statlayout,
                        refrsh, isFristInit, isRefrsh, isShowDialog, isCancel, emptyView, emptyView, errorView) {
                    @Override
                    protected void onBusinessSuccess(CategoryListBean categoryListBean) throws Exception {
                        if (categoryListBean != null) {
                            List<CategoryListBean.DataBean.ItemListBean> itemList = categoryListBean.getData().getItemList();
                            if(currentPage ==1) {
                                cateGoryGoodListAdapter.setNewData(itemList);
                            }else {
                                cateGoryGoodListAdapter.addData(itemList);
                            }
                            currentPage++;
                        }
                        int itemCount = cateGoryGoodListAdapter.getData().size();
                        if(categoryListBean.getData().getTotalRecord() == itemCount){//数据加载完成
                            cateGoryGoodListAdapter.loadMoreEnd(false);

                        }else {
                            cateGoryGoodListAdapter.loadMoreComplete();
                        }

                    }

                    @Override
                    protected void onChildFailure(Throwable e, boolean isNetWorkError) throws Exception {

                    }


                });
    }

    @Override
    public void onBackPressedSupport() {
        super.onBackPressedSupport();
        EventBus.getDefault().post("返回");
        finish();
    }

    @OnClick(R.id.search_et)
    public void search(View view){
        Intent intent = new Intent(this,SearchActivity.class);
        startActivity(intent);
    }
}
